#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
#include <ctime>
#include <vector>
using namespace std;

pthread_mutex_t mutex;
pthread_cond_t cond;

struct Node
{
    int val;
    Node *next;
    Node(int _val = 0) : val(_val), next(nullptr) {}
};

vector<Node *> table;

void Print(Node *h)
{
    cout <<"Producer-----------------The list is  ";
    while(h)
    {
        cout << h->val << " ";
        h = h->next;
    }
    cout << endl;
}

void *producer(void *argc)
{
    int bproduc = 1;
    while(1)
    {
        srand(time(NULL));
        int val = rand()%20;
        Node *cur = new Node(val);
    // 生产者生产
        pthread_mutex_lock(&mutex);
        cout << "Producer-----------------produce num is  " << cur->val << endl;
        table.push_back(cur);
        //Print(head);
        pthread_mutex_unlock(&mutex);
    // 生产完毕后唤醒消费者
        pthread_cond_signal(&cond);
        sleep(1);
    }
    return nullptr;
}

void *customer(void *argc)
{
    int acust = 1;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        while(table.empty())
        {
            cout << "Customer-----------------wait for producer " << endl;
            pthread_cond_wait(&cond, &mutex);
        }
        cout << "Customer-----------------customer start to consum" << endl;
    // 消费者开始消费
        Node *tmp = table.back();
        table.pop_back();
        cout << "Customer-----------------tmp == " << tmp->val << endl;
        pthread_mutex_unlock(&mutex);
        delete tmp;
        sleep(2);
    }
    return nullptr;
}

int main()
{
    pthread_t p1, c1;

    cout << "start the test process" << endl;  
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);     
    pthread_create(&p1, NULL, producer, NULL);
    pthread_create(&c1, NULL, customer, NULL);
    while(1);
    pthread_detach(p1);
    pthread_detach(c1);

    //    销毁工作 
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
}